﻿using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using vkUpploaderLib.Exceptions;
using vkUpploaderLib.Resourses;

namespace vkUpploaderLib
{
    using HttpHelpers;

    /// <summary>
    /// Contains all methods to autorize user in vk web-site
    /// </summary>
    public static class AuthHelper 
    {
        public const string AuthClientID = "2023445";
        public static readonly string AuthUrl =
            string.Format("http://api.vkontakte.ru/oauth/authorize?client_id={0}&scope=photos,groups&redirect_uri=http://api.vkontakte.ru/blank.html&display=popup&response_type=token", AuthClientID);


        public static string ErrorReason;
        public static string ErrorDescripton;
        public static string Error;
        public static string Token;
        public static DateTime TokenExpires;

        public static string ExpiresIn;
        public static string UserID;

        public static DateTime TokenObtained;



        public static event EventHandler<ErrorEventArgs> LoginError;

        public static bool Auth()
        {
            // TODO : return token information
            using (AuthWindow window = new AuthWindow(AuthUrl))
            {
                if (window.DialogResult == DialogResult.OK)
                {
                    return true;
                }
            }
            return false;
        }

     
        public static readonly string[] SeparatorsError = { "error=", "=", "&", "error_description", "error_reason" };
        public static readonly string[] SeparatorsSucceed = new[] { "access_token", "=", "&", "expires_in", "user_id" };


        /// <summary>
        /// http://vkontakte.ru/developers.php?o=-1&p=%C0%E2%F2%EE%F0%E8%E7%E0%F6%E8%FF%20%EA%EB%E8%E5%ED%F2%F1%EA%E8%F5%20%EF%F0%E8%EB%EE%E6%E5%ED%E8%E9
        /// </summary>
        /// <param name="url"></param>
        public static bool ProcessAuthResult(string url)
        {
            //error=access_denied&error_description=The+user+or+authorization+server+denied+the+request.
            if (IsError(url))
            {

                if (LoginError != null)
                {
                    LoginError(null, new ErrorEventArgs(new Exception(String.Format("{0}: {1}\n{2}: {3}\n{4}: {5}",
                                                      StringResources.Error, AuthHelper.Error,
                                                      StringResources.ErrorReason, AuthHelper.ErrorReason,
                                                      StringResources.ErrorDescription, AuthHelper.ErrorDescripton))));
                }
                return false;
            }
            return true;
        }

        private static bool IsError(string url)
        {
            if (url.Contains("error"))
            {
                string[] argsErr = url.Split(AuthHelper.SeparatorsError, StringSplitOptions.RemoveEmptyEntries)
                    .Skip(1)
                    .ToArray();
                AuthHelper.Error = argsErr[0];
                AuthHelper.ErrorReason = argsErr[1];
                AuthHelper.ErrorDescripton = argsErr[2];
                return true;
            }
            string[] args = url.Split(AuthHelper.SeparatorsSucceed, StringSplitOptions.RemoveEmptyEntries)
                .Skip(1)
                .ToArray();
            AuthHelper.Token = args[0];
            AuthHelper.ExpiresIn = args[1];
            AuthHelper.UserID = args[2];
            AuthHelper.TokenObtained = DateTime.Now;
            AuthHelper.TokenExpires = DateTime.Now + new TimeSpan(0, 0, 0, Int32.Parse(AuthHelper.ExpiresIn));

            return false;
        }

     

      


    }
}
